<template>
  <AuModal
    v-model="showUploadPopup"
    :title="t('store_manage.form.import_store')"
    :padding="false"
    v-bind="$attrs"
    @handleConfirm="submit"
    @click="closePopup"
  >
    <div class="flex justify-center py-[30px]">
      <el-upload
        ref="uploadRef"
        v-model:file-list="fileList"
        class="upload-demo"
        :on-change="before"
        action=""
        multiple
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-exceed="handleExceed"
        :limit="1"
        accept="xlsx,xls"
        :auto-upload="false"
      >
        <el-button type="primary"
          >{{ t("store_manage.form.upload_excel") }}
        </el-button>
        <template #tip>
          <div class="el-upload__tip">
            {{ t("store_manage.form.upload_file_type") }}
            <a
              :href="templateUrl"
              style="color: blue"
              download="门店导入_模版.xlsx"
              >{{ t("store_manage.form.store_import_template") }}</a
            >
          </div>
        </template>
      </el-upload>
    </div>
    <AuModal
      v-model="showError"
      :padding="false"
      width="460px"
      :showCancel="false"
      @handleConfirm="
        () => {
          showError = false;
          errorList = [];
        }
      "
      @close="
        () => {
          errorList = [];
        }
      "
    >
      <template #title>
        <div class="flex items-center text-[14px]">
          <span class="text-[40px] text-[--el-color-danger]">
            <IconifyIconOnline icon="pepicons-pop:exclamation-circle-filled" />
          </span>
          &emsp;{{ t("store_manage.form.error") }}
        </div>
      </template>
      <template #default>
        <el-scrollbar height="50vh">
          <div
            v-for="(item, i) in errorList"
            :key="i"
            class="first:mt-[20px] mt-[10px] px-[20px] last:mb-[10px]"
          >
            <div class="text-[14px] text-[--autata-font-gray-color] mb-[4px]">
              {{ t("store_manage.form.error_reason") }}{{ i + 1 }}
            </div>
            <component :is="item" class="text-[--autata-font-color]]" />
          </div>
        </el-scrollbar>
      </template>
    </AuModal>
  </AuModal>
</template>

<script setup lang="ts">
import { AuModal } from "@/components/AuModal";
import {
  getCurrentInstance,
  computed,
  ref,
  h,
  onMounted,
  onUnmounted
} from "vue";
import { getGroupList, addList } from "@/api/teaInfuser/store";
import { addStoreGroup, GroupProp } from "@/api/teaInfuser/store";
import * as xlsx from "xlsx";
import { useI18n } from "vue-i18n";

import {
  genFileId,
  UploadProps,
  UploadRawFile,
  UploadUserFile
} from "element-plus";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();
const { t } = useI18n();

const errorList = ref([]);
const showError = ref(false);

const uploadRef = ref(null);
onMounted(() => {
  console.log("已加载");
  fileList.value = [];
  getGroupSelectList();
  //storeDataList.value = null;
});

onUnmounted(() => {
  console.log("组件已卸载");
  fileList.value = [];
  storeDataList.value = null;
  // 执行清理操作
});

const templateUrl = "/admin/门店管理.xlsx";
const groupList = ref<GroupProp[]>([]);
const getGroupSelectList = async () => {
  const res = await getGroupList({
    start_page: 1,
    size: 0,
    hiddenDeviceType: true
  });
  groupList.value = res.data;
};

// 查找函数
const findObjectByProperty = (
  propertyName: string,
  value: string,
  parentId: number
) => {
  return groupList.value.find(
    obj => obj[propertyName] === value && obj.parent_id === parentId
  );
};

const storeDataList = ref();

const fileList = ref<UploadUserFile[]>([]);
const handlePreview: UploadProps["onPreview"] = uploadFile => {
  //console.log(uploadFile);
};

const handleRemove: UploadProps["onRemove"] = (file, fileLists) => {
  fileList.value = [];
  uploadRef.value?.clearFiles();
};

const handleExceed: UploadProps["onExceed"] = files => {
  uploadRef.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  uploadRef.value!.handleStart(file);
};
/**
 * 把文件按照二进制进行读取
 * @param file
 * @returns
 */
const readFile = (file: File) => {
  return new Promise(resolve => {
    let reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = ev => {
      resolve(ev.target?.result);
    };
    console.log(reader);
  });
};
/**
 * 根据sheet索引读取Excel文件中的数据
 /**@param file 文件
 /** @param sheetIndex excel文件中sheet表索引 默认是从0开始
 /**@returns  将表中的数据以json形式的数据返回
 */
const readExcelFile = async (file: File, sheetIndex: number) => {
  return new Promise(resolve => {
    readFile(file).then(data => {
      let workbook = xlsx.read(data, { type: "binary" });
      let worksheet = workbook.Sheets[workbook.SheetNames[sheetIndex]];
      data = xlsx.utils.sheet_to_json(worksheet);
      resolve(data);
    });
  });
  /* let data = await readFile(file);
  let workbook = xlsx.read(data, { type: "binary" });
  let worksheet = workbook.Sheets[workbook.SheetNames[sheetIndex]];
  data = xlsx.utils.sheet_to_json(worksheet);
  console.log(data);
  return data; */
};
const before = (file: any) => {
  /* readExcelFile(file, 0).then(res => (storeDataList.value = res));

  return false; */
  const reader = new FileReader();
  reader.onload = e => {
    const data = e.target.result;
    const workbook = xlsx.read(data, { type: "array" });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const results = xlsx.utils.sheet_to_json(worksheet);
    storeDataList.value = results;
    ElMessage({
      message: t("store_manage.form.upload_success"),
      type: "success"
    });
  };
  reader.readAsArrayBuffer(file.raw);
};

interface Props {
  modelValue: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false
});

const emit = defineEmits(["update:modelValue", "handleConfirm"]);

const showUploadPopup = computed({
  get() {
    return props.modelValue;
  },
  set(val: boolean) {
    emit("update:modelValue", val);
  }
});

const uploadTitle = ref("导入门店");

const formRef = ref();

const provinceCity = ref([]);

/* const getCityList = (val: string) => {
  if (val) {
    const find = provinceCity.value.find(item => item.value === val);
    storeFormRef.value.setFormProps("city", {
      options: find?.children ?? []
    });
  }
}; */

// 辅助函数：校验不为空
const check = async (storeList: any[]) => {
  const msgList = [];

  const duplicates = [];

  for (let i = 0; i < storeList.length; i++) {
    //判断门店名称是否为空
    if (
      storeList[i].门店名称 == null ||
      storeList[i].门店名称 == undefined ||
      storeList[i].门店名称.trim() == ""
    ) {
      const msg = h("p", { style: "line-height: 2; font-size: 14px" }, [
        h("span", null, `第${i + 1}个门店名称不能为空`)
      ]);

      msgList.push(msg);
    }
    //判断省
    if (
      storeList[i].省份 == null ||
      storeList[i].省份 == undefined ||
      storeList[i].省份.trim() == ""
    ) {
      const msg = h("p", { style: "line-height: 2; font-size: 14px" }, [
        // h("span", null, `第${i + 1}个门店省份不能为空`)
        h(
          "span",
          null,
          t("store_manage.form.province_not_empty", { index: i + 1 })
        )
      ]);

      msgList.push(msg);
    }

    //判断城市
    if (
      storeList[i].城市 == null ||
      storeList[i].城市 == undefined ||
      storeList[i].城市.trim() == ""
    ) {
      const msg = h("p", { style: "line-height: 2; font-size: 14px" }, [
        // h("span", null, `第${i + 1}个门店城市不能为空`)
        h("span", null, t("store_manage.form.city_not_empty", { index: i + 1 }))
      ]);

      msgList.push(msg);
    }

    //判断分组层级
    if (
      storeList[i].门店分组 != null &&
      storeList[i].门店分组 != undefined &&
      storeList[i].门店分组.trim() != ""
    ) {
      const groupitem = storeList[i].门店分组;
      //处理分组
      const groupArr = groupitem.split("-");

      if (groupArr.length < 2) {
        const msg = h("p", { style: "line-height: 2; font-size: 14px" }, [
          // h("span", null, `第${i + 1}个门店分组填写不规范`)
          h(
            "span",
            null,
            t("store_manage.form.group_format_error", { index: i + 1 })
          )
        ]);

        msgList.push(msg);
      }
    }

    //判断省市详细地址是否有重复的
    const itemMap = {
      address: storeList[i].省份 + storeList[i].城市 + storeList[i].详细地址,
      index: i + 1
    };
    if (i == 0) {
      duplicates.push(itemMap);
    } else {
      if (hasMatchingProperty(duplicates, "address", itemMap.address)) {
        const msg = h("p", { style: "line-height: 2; font-size: 14px" }, [
          // h("span", null, `第${i + 1}个门店省份、城市、详细地址填写重复`)
          h(
            "span",
            null,
            t("store_manage.form.address_duplicate", { index: i + 1 })
          )
        ]);

        msgList.push(msg);
      } else {
        duplicates.push(itemMap);
      }
    }
  }

  return msgList;
};

const hasMatchingProperty = (array, propertyName, value) => {
  return array.some(item => item[propertyName] === value);
};

const submit = async (data: any) => {
  //emit("submit", data);
  if (storeDataList.value == undefined) {
    ElMessage({
      message: t("store_manage.form.upload_data_file"),
      type: "error"
    });
  }

  let storeList = [];

  //校验
  let errList = [];

  const checkRes = await check(storeDataList.value);
  if (checkRes.length) {
    errList.push(...checkRes);
  }

  if (errList.length > 0) {
    showError.value = true;
    errorList.value = errList;

    return;
  }

  /* for (const item of storeDataList.value) {
    await getGroupSelectList();
    const formData = new FormData();
    formData.append("name", item.门店名称);

    formData.append("province", item.省份);

    formData.append("city", item.城市);
    formData.append("detail_address", item.详细地址);
    formData.append("operator", item.店长);
    formData.append("phone", item.手机号);

    const groupitem = item.门店分组;
    //处理分组
    const groupArr = groupitem.split("-");

    if (groupArr.length < 2) {
      ElMessage({
        message: "分组填写有误",
        type: "error"
      });
      return false;
    } else {
      let parentId = 0;
      for (let fzIndex = 1; fzIndex < groupArr.length; fzIndex++) {
        const tempResult = findObjectByProperty(
          "name",
          groupArr[fzIndex],
          parentId
        );
        console.log(tempResult);
        if (tempResult == undefined) {
          //不存在新增
          const tempGroupData = new FormData();
          tempGroupData.append("parent_id", String(parentId));
          tempGroupData.append("name", groupArr[fzIndex]);
          tempGroupData.append("info", "");
          tempGroupData.append("device_type", " 泡茶机");

          const tempGrpRes = await addStoreGroup(tempGroupData);

          if (fzIndex == groupArr.length - 1) {
            //最后一层插入门店
            //开始插入门店
            formData.append("group_id", String(tempGrpRes.data.id));
            //保存

            const storeRes = await addStore(formData);
            if (storeRes.code === 200) {
              emit("handleConfirm");
            }
          } else {
            parentId = tempGrpRes.data.id;
          }
        } else {
          if (fzIndex == groupArr.length - 1) {
            //最后一层插入门店
            //开始插入门店
            formData.append("group_id", String(tempResult.id));
            //保存

            const storeRes = await addStore(formData);
            if (storeRes.code === 200) {
              emit("handleConfirm");
            }
          } else {
            parentId = tempResult.id;
          }
        }
      }
    }
  } */

  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)"
  });

  for (const item of storeDataList.value) {
    await getGroupSelectList();
    let jsonData = {};
    const formData = new FormData();
    formData.append("name", item.门店名称);

    formData.append("province", item.省份);

    formData.append("city", item.城市);
    formData.append("detail_address", item.详细地址);
    formData.append("operator", item.店长);
    formData.append("phone", item.手机号);

    const groupitem = item.门店分组;
    //处理分组
    const groupArr = groupitem.split("-");

    if (groupArr.length < 2) {
      ElMessage({
        message: t("store_manage.form.group_length_error"),
        type: "error"
      });
      return false;
    } else {
      let parentId = 0;
      for (let fzIndex = 1; fzIndex < groupArr.length; fzIndex++) {
        const tempResult = findObjectByProperty(
          "name",
          groupArr[fzIndex],
          parentId
        );
        console.log(tempResult);
        if (tempResult == undefined) {
          //不存在新增
          const tempGroupData = new FormData();
          tempGroupData.append("parent_id", String(parentId));
          tempGroupData.append("name", groupArr[fzIndex]);
          tempGroupData.append("info", "");
          tempGroupData.append("device_type", " 泡茶机");

          const tempGrpRes = await addStoreGroup(tempGroupData);

          if (fzIndex == groupArr.length - 1) {
            //最后一层插入门店
            //开始插入门店
            formData.append("group_id", String(tempGrpRes.data.id));

            jsonData = {
              group_id: String(tempGrpRes.data.id),
              name: item.门店名称,
              province: item.省份,
              city: item.城市,
              detail_address: item.详细地址,
              operator: item.店长,
              phone: item.手机号
            };
            //保存
            storeList.push(jsonData); //添加到门店列表
            /* const storeRes = await addStore(formData);
            if (storeRes.code === 200) {
              emit("handleConfirm");
            } */
          } else {
            parentId = tempGrpRes.data.id;
          }
        } else {
          if (fzIndex == groupArr.length - 1) {
            //最后一层插入门店
            //开始插入门店
            formData.append("group_id", String(tempResult.id));
            jsonData = {
              group_id: String(tempResult.id),
              name: item.门店名称,
              province: item.省份,
              city: item.城市,
              detail_address: item.详细地址,
              operator: item.店长,
              phone: item.手机号
            };
            //保存
            storeList.push(jsonData); //添加到门店列表
            /* const storeRes = await addStore(formData);
            if (storeRes.code === 200) {
              emit("handleConfirm");
            } */
          } else {
            parentId = tempResult.id;
          }
        }
      }
    }
  }

  /* const addListParam = {
    storeParams: storeList
  }; */
  try {
    errorList.value = [];
    const res = await addList(storeList);
    loading.close();
    let successFlag = true;
    for (let errorIndex = 0; errorIndex < res.data.length; errorIndex++) {
      if (res.data[errorIndex].success == false) {
        successFlag = false;
        errorList.value.push(h("p", {}, res.data[errorIndex].message));
      }
    }

    console.log(successFlag);

    if (successFlag) {
      emit("handleConfirm");
      uploadRef.value.clearFiles();
      storeDataList.value = null;
      fileList.value = [];
      ElMessage({
        message: t("store_manage.form.import_success"),
        type: "success"
      });
    } else {
      console.log(successFlag);
      console.log(errorList.value);
      uploadRef.value.clearFiles();
      storeDataList.value = null;
      fileList.value = [];
      showError.value = true;
    }

    /* if (res.code == 200) {
      emit("handleConfirm");
      uploadRef.value.clearFiles();
      storeDataList.value = null;
      fileList.value = [];
      ElMessage({
        message: "导入成功",
        type: "success"
      });
    } else {
      loading.close();
      //emit("handleConfirm");

      uploadRef.value.clearFiles();
      storeDataList.value = null;
      fileList.value = [];

      errorList.value = [];
      errorList.value.push(h("p", {}, res.message));
      showError.value = true;
    }*/
  } catch (error) {}

  //emit("handleConfirm");
};
const closePopup = () => {
  console.log("关闭");
};

const closeErrorDialog = () => {
  showError.value = false;
  errorList.value = [];
};
</script>
